package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AppOpsManager;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.StrictMode;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.EventWatcher;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.MyFragmentPagerAdapter2;
import com.jdy.haoduoai.enums.MediaType;
import com.jdy.haoduoai.enums.PlayState;
import com.jdy.haoduoai.fragment.BaseFragment;
import com.jdy.haoduoai.fragment.TabIndexFragment;
import com.jdy.haoduoai.fragment.TabMineFragment;
import com.jdy.haoduoai.fragment.TabNewDiscoverFragment;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.AppVersion;
import com.jdy.haoduoai.model.AudioItem;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PainPointItem;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.service.Net_Service;
import com.jdy.haoduoai.socket.DeviceStateListener;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.ACache;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.OnDataReceivedListener;
import com.jdy.haoduoai.util.PathUtil;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.CustomViewPager;
import com.jdy.haoduoai.view.visualizer.FrequencyDistributionBarView;
import com.jdy.haoduoai.widget.CustomUpdateDialog;
import com.nineoldandroids.view.ViewHelper;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.android.tpush.service.XGPushService;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;

//import com.jdy.haoduoai.R;

//import com.jdy.haoduoai.fragment.TabAnimationFragment;

/**
 * 
 * 
 * @author hf
 * 
 */
@SuppressLint({ "InflateParams", "HandlerLeak", "ClickableViewAccessibility" })
public class MainActivity extends BaseActivity implements OnClickListener,
    /*IMParseListener,*/ OnDataReceivedListener, DeviceStateListener {

  private Handler mHandler = new Handler();
  @SuppressWarnings("unused")
  private DisplayImageOptions options;
  @InjectView(id = R.id.viewpager)
  private CustomViewPager viewPager;
  @InjectView(id = R.id.radiogroup)
  private RadioGroup radioGroup;
  @InjectView(id = R.id.radio_1)
  private RadioButton radio_1;
  //  @InjectView(id = R.id.radio_2)
//  private RadioButton radio_2;
  @InjectView(id = R.id.radio_3)
  private RadioButton radio_3;
  @InjectView(id = R.id.radio_4)
  private RadioButton radio_4;
  @InjectView(id = R.id.title_layout)
  private View title_layout;
  @InjectView(id = R.id.img_redicon)
  private ImageView img_redicon;
  @InjectView(id = R.id.img_qiandao, click = true)
  private ImageView img_qiandao;
  @InjectView(id = R.id.device_stateview, click = true)
  private FrequencyDistributionBarView device_stateview;
  @InjectView(id = R.id.tv_recustom, click = true)
  private TextView tv_recustom;

  private TextView tv_soundnum;
  private View frame_soundmsg;

  @InjectView(id = R.id.playbackryl)
  private RelativeLayout playbackryl;
  @InjectView(id = R.id.titles)
  private TextView audioname;
  @InjectView(id = R.id.playmode, click = true)
  private ImageView playmode;
  @InjectView(id = R.id.img_search, click = true)
  private ImageView img_search;
  @InjectView(id = R.id.drawer_main_content_frame)
  private DrawerLayout mDrawerLayout;
  @InjectView(id = R.id.emptylayout, click = true)
  private LinearLayout emptylayout;
  @InjectView(id = R.id.content_frame)
  private View content_frame;
  @InjectView(id = R.id.reloadRippleView, click = true)
  private View reloadRippleView;


  private TextView tv_iknow;
  private View rel_sleeptip;

  private List<BaseFragment> fragmentList = new ArrayList<BaseFragment>();
  // private CustomProgressDialog mProgressDialog;
  boolean isExitReady = false;
  private boolean mReceiverTag = false;
  // private CustomHomeDialog mCustomClassTipDlg;
  private LeUser mLeUser;

  private AudioItem audioItem = null;

  private ReceiverHandler rh;
  // private ENUM_PAGE mLastIndex = ENUM_PAGE.HOME_PAGE;
  private ENUM_PAGE mCurrentIndex = ENUM_PAGE.HOME_PAGE;

  private enum ENUM_PAGE {
    HOME_PAGE, DISCOVERY, PERSON_CENTER
  }

  float mValueAvatar;


  @SuppressWarnings("unused")
  private MediaType mMediaType = MediaType.None;

  // private LeSocketManagerService bindService;


  private IntentFilter intentFilter;
  private ExitJzdBroadcastReceiver myBroadcastReceiver;
  public static final String BROADCAST_ACTIONEXITxxj ="exitJZD";


  @TargetApi(Build.VERSION_CODES.KITKAT)
  private boolean isNotificationEnabled(Context context) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
      String CHECK_OP_NO_THROW = "checkOpNoThrow";
      String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

      AppOpsManager mAppOps = (AppOpsManager) context
              .getSystemService(Context.APP_OPS_SERVICE);
      ApplicationInfo appInfo = context.getApplicationInfo();
      String pkg = context.getApplicationContext().getPackageName();
      int uid = appInfo.uid;

      Class appOpsClass = null;
      /* Context.APP_OPS_MANAGER */
      try {
        appOpsClass = Class.forName(AppOpsManager.class.getName());
        Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW,
                Integer.TYPE, Integer.TYPE, String.class);
        Field opPostNotificationValue = appOpsClass
                .getDeclaredField(OP_POST_NOTIFICATION);

        int value = (Integer) opPostNotificationValue.get(Integer.class);
        return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (NoSuchFieldException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
      return false;
    } else {
      return true;
    }
  }

  @SuppressLint("MissingSuperCall")
  @Override
  protected void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
    // super.onSaveInstanceState(outState);
  }

  @Override
  protected void onRestart() {
    if (rel_sleeptip.getVisibility() == View.VISIBLE) {
      rel_sleeptip.startAnimation(mBottomDownAnimation);
    }

    super.onRestart();
  }

  Animation mBottomUpAnimation; //= AnimationUtils.loadAnimation(this, R.anim.footer_appear);
  Animation mBottomDownAnimation; // = AnimationUtils.loadAnimation(this, R.anim.bottom_down_out);

  @SuppressWarnings("unchecked")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFormat(PixelFormat.TRANSLUCENT);
    this.setContentView(R.layout.activity_main_xxb);

    if (Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
              .permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }

    registerCast();//注册广播
    hideTitleView();

    Intent intent = getIntent();
    if (intent != null) {
      nonetwork = intent.getBooleanExtra("nonetwork", false);
    }

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    LeXiaoXiaoBanApp.getInstance().screenW = dm.widthPixels;
    LeXiaoXiaoBanApp.getInstance().screenH = dm.heightPixels;

    mBottomUpAnimation = AnimationUtils.loadAnimation(this, R.anim.footer_appear);
    mBottomDownAnimation = AnimationUtils.loadAnimation(this, R.anim.footer_disappear);

    tv_iknow = (TextView) findViewById(R.id.tv_iknow);
    tv_iknow.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        // TODO
        // rel_sleeptip.setVisibility(View.GONE);
        rel_sleeptip.startAnimation(mBottomDownAnimation);

        ACache mCache = ACache.get(MainActivity.this);
        mCache.put("clickIKnow", "clickIKnow", Tools.getMiao());//超过当天剩余秒去获取这个key，将为null
      }
    });


    rel_sleeptip = findViewById(R.id.rel_sleeptip);
    if (!Tools.isDayTime()) {
      ACache mCache = ACache.get(MainActivity.this);
      if (Tools.isNullStr(mCache.getAsString("clickIKnow"))) {
        mHandler.postDelayed(new Runnable() {
          @Override
          public void run() {
            rel_sleeptip.startAnimation(mBottomUpAnimation);
          }
        }, 1500);
      } else {
        rel_sleeptip.setVisibility(View.GONE);
      }
    } else {
      rel_sleeptip.setVisibility(View.GONE);
    }


    mBottomUpAnimation.setAnimationListener(new AnimationListener() {
      @Override
      public void onAnimationStart(Animation animation) {
        // TODO
        rel_sleeptip.setVisibility(View.VISIBLE);
      }

      @Override
      public void onAnimationRepeat(Animation animation) {
        // TODO

      }

      @Override
      public void onAnimationEnd(Animation animation) {
        // TODO
      }
    });


    mBottomDownAnimation.setAnimationListener(new AnimationListener() {
      @Override
      public void onAnimationStart(Animation animation) {
        // TODO

      }

      @Override
      public void onAnimationRepeat(Animation animation) {
        // TODO

      }

      @Override
      public void onAnimationEnd(Animation animation) {
        rel_sleeptip.setVisibility(View.GONE);
      }
    });


    radio_1.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
              @SuppressWarnings("deprecation")
              @Override
              public void onGlobalLayout() {
                radio_1.getWidth();
                radio_1.getHeight();

                if (img_redicon == null) {
                  img_redicon = (ImageView) findViewById(R.id.img_redicon);
                }

                ViewHelper.setTranslationX(img_redicon, radio_1.getWidth() / 2
                        + Tools.getPixelByDip(MainActivity.this, 5));

                ViewHelper.setTranslationY(img_redicon, -radio_1.getHeight()
                        + Tools.getPixelByDip(MainActivity.this, 5));

                radio_1.getViewTreeObserver().removeGlobalOnLayoutListener(this);
              }
            });

    reloadRippleView = emptylayout.findViewById(R.id.reloadRippleView);
    reloadRippleView.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        if (Tools.isNetworkAvailable(MainActivity.this)) {
          silentLogin();
        } else {
          toastShow("请检查网络连接");
        }
      }
    });

    if (!Tools.isNetworkAvailable(MainActivity.this) || nonetwork) {
      emptylayout.setVisibility(View.VISIBLE);
      content_frame.setVisibility(View.GONE);
    } else {
      emptylayout.setVisibility(View.GONE);
      content_frame.setVisibility(View.VISIBLE);
      doInit();
    }

    if (mLeUser != null && Tools.isNotEmpty(mLeUser.avatar)) {
      getHeadImage(mLeUser.avatar, true);
    }

//    checkForNewestVersion();

    if (!isNotificationEnabled(this)) {
      showNotificationTipDialog();
    }

    long lastLaunchTime = LePreference.getInstance().getLong("lastLaunchTime",
            0);
    if (lastLaunchTime > 0) {
      long diff = System.currentTimeMillis() - lastLaunchTime;
      long days = diff / (1000 * 60 * 60 * 24);

      if (days >= 1) {
        String jsonStr = LePreference.getInstance().getString(
                "selectedpainpoint");
        if (Tools.isNotEmpty(jsonStr)) {
          painPointlistt = (ArrayList<PainPointItem>) JsonSerializer
                  .getInstance().deserialize(jsonStr, ArrayList.class,
                          PainPointItem.class);

          if (painPointlistt != null && !painPointlistt.isEmpty()) {
            showTaskResultDlgDialog(days);
          }
        }
      }
    }
  }

  /**
   * 创建退出小小金的广播
   */
  private void registerCast() {
    intentFilter = new IntentFilter();
    intentFilter.addAction("exitJZD");
    myBroadcastReceiver = new ExitJzdBroadcastReceiver();
    registerReceiver(myBroadcastReceiver, intentFilter);

  }


  /**
   * 广播
   */
  public class ExitJzdBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
      //收到广播受重新刷新页面数据
      if (BROADCAST_ACTIONEXITxxj.equals(intent.getAction())) {
        finish();
        Log.e("TEST", "RUN");
      }
    }
  }


  private ArrayList<PainPointItem> painPointlistt;

  public void showNotificationTipDialog() {
    LayoutInflater inflater = getLayoutInflater();
    final View layout = inflater.inflate(R.layout.notification_dlg, null);// 获取自定义布局
    Button button = (Button) layout.findViewById(R.id.button);
    button.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    button.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {
        if (notificationTipDlg != null) {
          notificationTipDlg.dismiss();
          notificationTipDlg = null;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
          Intent intent = new Intent(Settings.ACTION_SETTINGS);
          startActivity(intent);
          return;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
          Intent intent = new Intent(Settings.ACTION_SETTINGS);
          startActivity(intent);
          return;
        }
      }
    });

    notificationTipDlg = new Dialog(this, R.style.custom_dialog);
    notificationTipDlg.setContentView(layout);
    notificationTipDlg.setCancelable(true);
    notificationTipDlg.show();
  }

  private Dialog notificationTipDlg;
  private Dialog taskResultDlg;

  @SuppressWarnings("unused")
  public void showTaskResultDlgDialog(long days) {
    LayoutInflater inflater = getLayoutInflater();
    final View layout = inflater.inflate(R.layout.taskresult_dlg, null);// 获取自定义布局

    TextView tv_days = (TextView) layout.findViewById(R.id.tv_days);
    TextView tv_stars = (TextView) layout.findViewById(R.id.tv_stars);

    LinearLayout linContent = (LinearLayout) layout
            .findViewById(R.id.rating_content);
    linContent.removeAllViews();

    for (int i = 0; i < painPointlistt.size(); i++) {
      LinearLayout lyout = (LinearLayout) LayoutInflater.from(this).inflate(
              R.layout.listitem_taskresult, linContent, false);

      TextView tv_label = (TextView) lyout.findViewById(R.id.tv_label);
      TextView tv_plus = (TextView) lyout.findViewById(R.id.tv_plus);
      ImageView img_painpoint = (ImageView) lyout
              .findViewById(R.id.img_painpoint);
      ImageView img1 = (ImageView) lyout.findViewById(R.id.img1);
      ImageView img2 = (ImageView) lyout.findViewById(R.id.img2);
      ImageView img3 = (ImageView) lyout.findViewById(R.id.img3);
      ImageView img4 = (ImageView) lyout.findViewById(R.id.img4);

      if (painPointlistt.get(i).name.contains("爱劳动")) {
        img_painpoint.setImageResource(R.drawable.aizhengjie);
      } else if (painPointlistt.get(i).name.contains("早睡早起")) {
        img_painpoint.setImageResource(R.drawable.zaoshuizaoqi);
      } else if (painPointlistt.get(i).name.contains("早晚刷牙")) {
        img_painpoint.setImageResource(R.drawable.aishuaya);
      } else if (painPointlistt.get(i).name.contains("不挑食")) {
        img_painpoint.setImageResource(R.drawable.butiaoshi);
      } else if (painPointlistt.get(i).name.contains("乐于分享")) {
        img_painpoint.setImageResource(R.drawable.leyufenxiang);
      } else if (painPointlistt.get(i).name.contains("独立意识")) {
        img_painpoint.setImageResource(R.drawable.dulizhizhu);
      } else if (painPointlistt.get(i).name.contains("注意安全")) {
        img_painpoint.setImageResource(R.drawable.zhuyianquan);
      } else if (painPointlistt.get(i).name.contains("情绪")) {
        img_painpoint.setImageResource(R.drawable.qingxuzikong);
      } else if (painPointlistt.get(i).name.contains("专注")) {
        img_painpoint.setImageResource(R.drawable.zhuanzhuyongxin);
      } else if (painPointlistt.get(i).name.contains("尊敬长辈")) {
        img_painpoint.setImageResource(R.drawable.zunjinzhangbei);
      }

      if (painPointlistt.get(i).name.length() < 4) {
        String strCont = "";
        for (int jj = 0; jj < (4 - painPointlistt.get(i).name.length()); jj++) {
          strCont += "\u3000";
        }
        tv_label.setText(strCont + painPointlistt.get(i).name + "：");
      } else {
        tv_label.setText(painPointlistt.get(i).name + "：");
      }

      if (days == 1) {
        img2.setVisibility(View.GONE);
        img3.setVisibility(View.GONE);
        img4.setVisibility(View.GONE);
        tv_plus.setVisibility(View.GONE);
      } else if (days == 2) {
        img3.setVisibility(View.GONE);
        img4.setVisibility(View.GONE);
        tv_plus.setVisibility(View.GONE);
      } else if (days == 3) {
        img4.setVisibility(View.GONE);
        tv_plus.setVisibility(View.GONE);
      } else if (days == 4) {
        tv_plus.setVisibility(View.GONE);
      } else {
        tv_plus.setText("+" + (days - 4));
      }

      linContent.addView(lyout);
    }

    tv_days.setText("距离上次打开APP已经" + days + "天");
    tv_stars.setText("可以给宝宝贴" + days + "颗星星");

    Button btn_close = (Button) layout.findViewById(R.id.btn_close);
    btn_close.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    btn_close.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {
        if (taskResultDlg != null) {
          taskResultDlg.dismiss();
          taskResultDlg = null;
        }
      }
    });

    taskResultDlg = new Dialog(this, R.style.custom_dialog);
    taskResultDlg.setContentView(layout);
    taskResultDlg.setCancelable(false);
    taskResultDlg.show();
  }

  private void doInit() {
    enableNetworkChangeListener();
    onActive();
    initialize();
    initListener();

    registerXG();

    String firstTip = LePreference.getInstance().getString("firstTip");
    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    if (mLeUser != null) {
      if (mLeUser.machine != null && mLeUser.machine.have_to_test
              || Tools.isEmpty(mLeUser.machine)) {
        if (Tools.isEmpty(firstTip)) {
          LePreference.getInstance().save("firstTip", "1");
          // showCustomClassTipDlg();
        }
      }
    }
  }

  private void silentLogin() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public ResponseResult doInbackground(Activity activity) {
        SharedPreferences prefs = activity.getSharedPreferences(
                Constant.USER_INFO, Context.MODE_PRIVATE);

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_MOBILE_I, prefs.getString(Constant.TEL, ""));
        param_.put(HttpUtils.TAG_PWD_I, prefs.getString(Constant.PWD, ""));
        param_.put(HttpUtils.TAG_PLATFORM_I, "android");
        param_.put(HttpUtils.TAG_TOKEN_I, "test");
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequestEncrypt(HttpUtils.API_URL
                + HttpUtils.LOGIN_METHOD_POST, param_, HttpUtils.TAG_POST_REQUEST);
      }

      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        MobclickAgent.onEvent(MainActivity.this,
                EventWatcher.EVENT_XIAOXIAOBAN_LOGIN);

        if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
          LeConfig.isLogin = true;

          LeUser lu = JsonSerializer.getInstance().deserialize(result.data,
                  LeUser.class);

          LeMachine lbaby = null;
          if (lu != null) {
            lbaby = lu.machine;
          }

          LeXiaoXiaoBanApp.getInstance().setBaby(lbaby);

          if (lbaby != null && !lbaby.toString().equals("null")
                  && Tools.isNotEmpty(lbaby.id)) {
            LeConfig.isDeviceBinded = true;
            LeConfig.MAC_ID = lbaby.id;
            LeConfig.babyname = lbaby.name;

            getBabyAvatar(lbaby.avatar);

            String url = lbaby.ip;
            if (Tools.isNotNullStr(url)) {
              StringTokenizer tokens = new StringTokenizer(url, ":");
              LeConfig.g_ServerIP = tokens.nextToken();
              LeConfig.FILE_PORT = Integer.parseInt(tokens.nextToken());
              final SocketThreadManager stm =
                      SocketThreadManager.getInstance();
              stm.setDeviceStateListener(MainActivity.this);
              stm.requestDeviceDetails();
            }

            if (lu != null && Tools.isNotEmpty(lu.nickname)
                    && Tools.isNotEmpty(lbaby.name)) {
              LeConfig.isInfoFilled = true;

              if (Tools.isNotEmpty(lbaby.activate)
                      && !lbaby.activate.toString().equals("null")) {
                LeConfig.isDeviceActivated = !lbaby.activate.is_expired;
                LeConfig.expiredAt = lbaby.activate.expired_at;
              }
            } else {
              LeConfig.isInfoFilled = false;
            }

          } else {
            LeConfig.isDeviceBinded = false;
          }

          if (lu != null) {
            LeConfig.PHONE_NUM = lu.id;
            LeConfig.nickname = lu.nickname;
          }

          LeXiaoXiaoBanApp.getInstance().setUser(lu);
          Tools.saveLeUser(lu);
          Tools.saveLeBaby(lbaby);

          Intent intent = new Intent("com.jdy.haoduoai.activity.login");
          sendBroadcast(intent);

          if (lu != null && Tools.isNotEmpty(lu.avatar)) {
            getHeadImage(lu.avatar, false);
          } else {
            dismissLoading();
            toastShow("登录成功!");
            doPageRoute();
          }

        } else { // 登录失败
          if (Tools.isNotNullStr(result.data)) {
            toastShow(result.data);
          }

//          Intent intent = new Intent(MainActivity.this, LoginActivity.class);
//          intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//          startActivity(intent);

//          finish();
        }

      }
    }).execute();
  }

  private void getHeadImage(String remoteHeadImageFilePath,
                            final boolean getImageOnly) {

    if (Tools.isNullStr(remoteHeadImageFilePath)) {
      return;
    }

    new AsyncTask<String, Void, Bitmap>() {
      @Override
      protected void onPostExecute(Bitmap result) {
        if (result != null) {
          String path = PathUtil.getElderAvatarPath(getApplicationContext());
          FileOutputStream out = null;
          try {
            File parentAvatarFile = new File(path);
            if (!parentAvatarFile.exists()) {
              parentAvatarFile.createNewFile();
            }
            out = new FileOutputStream(parentAvatarFile);
            result.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is
            // your
            // Bitmap
            // instance
            // PNG is a lossless format, the compression factor (100) is
            // ignored
            SharedPreferences prefs = getSharedPreferences(Constant.USER_INFO,
                    Context.MODE_PRIVATE);
            Uri parentAvatarUri = Uri.fromFile(parentAvatarFile);
            prefs.edit()
                    .putString(Constant.PARENT_AVATAR, parentAvatarUri.toString())
                    .apply();
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            try {
              if (out != null) {
                out.close();
              }
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }

        dismissLoading();

        if (!getImageOnly) {
          toastShow("登录成功!");

          doPageRoute();
        }
      }

      @Override
      protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap resultImage = null;
        URL url;
        try {
          url = new URL(urldisplay);

          HttpURLConnection urlConnection = (HttpURLConnection) url
                  .openConnection();

          urlConnection.setRequestMethod("GET");
          // urlConnection.setDoOutput(true);
          urlConnection.connect();

          InputStream in = urlConnection.getInputStream();
          resultImage = BitmapFactory.decodeStream(in);

        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        return resultImage;
      }
    }.execute(remoteHeadImageFilePath);

  }

  private void doPageRoute() {
    if (LeConfig.isLogin) {
      if (LeConfig.isDeviceBinded) {
        if (LeConfig.isInfoFilled) {
          if (LeConfig.isDeviceActivated) {

          } else {
            // TODO
          }

          emptylayout.setVisibility(View.GONE);
          content_frame.setVisibility(View.VISIBLE);
          doInit();
        } else {
          Intent t = new Intent(MainActivity.this, FillInfoPopupActivity.class);
          startActivity(t);
          // finish();
        }
      } else {
        Intent t = new Intent(MainActivity.this, ConnectWifiActivity.class);
        startActivity(t);
        // finish();
      }
    } else {
      // TODO
    }
  }

  private void registerToken(final String token) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          Log.d("TPush", "Response data is:" + result.data.toString());
        }
      }

      @SuppressWarnings("unused")
      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        int age = 0;
        String apellationName = null, nickname = null, headImage = null;
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        if (age != 0) {
          param_.put(HttpUtils.TAG_AGE_I, String.valueOf(age));
        }
        if (apellationName != null) {
          param_.put(HttpUtils.TAG_APPELLATION_NAME_I, apellationName);
        }
        if (nickname != null) {
          param_.put(HttpUtils.TAG_NICK_NAME_I, nickname);
        }
        if (headImage != null) {
          param_.put(HttpUtils.TAG_HEAD_IMAGE_I, headImage);
        }
        param_.put(HttpUtils.TAG_PLATFORM_I, "android");
        if (Tools.isNotEmpty(token)) {
          param_.put(HttpUtils.TAG_TOKEN_I, token);
        }

        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        return HttpUtils.startRequest(HttpUtils.API_URL
                        + HttpUtils.UPDATE_PARENT_METHOD_PUT + mLeUser.sno, param_,
                HttpUtils.TAG_PUT_REQUEST);

      }
    }).execute();
  }

  private void registerXG() {
    XGPushManager.registerPush(getApplicationContext(),
            new XGIOperateCallback() {
              @Override
              public void onSuccess(Object data, int flag) {
                Log.d("TPush", "注册成功，设备token为：" + data.toString());
                LeConfig.XG_TOKEN = data.toString();

                if (LeConfig.isLogin) {
                  registerToken(LeConfig.XG_TOKEN);
                }
              }

              @Override
              public void onFail(Object data, int errCode, String msg) {
                Log.d("TPush", "注册失败，错误码：" + errCode + ",错误信息：" + msg);
              }
            });

    Intent service = new Intent(this, XGPushService.class);
    startService(service);
  }

  private void initListener() {

  }

  private void initialize() {
    if (device_stateview == null) {
      device_stateview = (FrequencyDistributionBarView) title_layout
              .findViewById(R.id.device_stateview);
    }

    tv_soundnum = (TextView) title_layout.findViewById(R.id.tv_soundnum);
    frame_soundmsg = title_layout.findViewById(R.id.frame_soundmsg);
    frame_soundmsg.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    frame_soundmsg.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, SpeakForYouActivity.class);
        startActivity(intent);
      }
    });

    device_stateview.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    img_qiandao.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    img_search.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

    // sp = getSharedPreferences("test", Activity.MODE_PRIVATE);
    rh = new ReceiverHandler(this);

    if (!mReceiverTag) {
      rh.registerAction(LeConfig.QuitPopuWindow);
      rh.registerAction("sound_msg_received");
      rh.registerAction("com.jdy.haoduoai.speed");
      rh.registerAction("com.jdy.haoduoai.activity.NOTIFICATION_SHOW");
      mReceiverTag = true;
    }

    options = new DisplayImageOptions.Builder()
            .showImageOnFail(R.drawable.default_img_listitem) // 下载
            .cacheInMemory(true) // 缓存
            .bitmapConfig(Bitmap.Config.RGB_565) // 图片格式
            .build();
    audioItem = new AudioItem();
    audioItem.second = 50;
    audioItem.name = "猫与老鼠";
    audioItem.url = "https://www.baidu.com/";
    audioItem.img_url = "http://c.hiphotos.baidu.com/image/pic/item/b8014a90f603738d3bf04b2ab11bb051f819ec04.jpg";
    // playAudio(audioItem);
  }

  @Override
  protected void onPause() {
    super.onPause();

    MobclickAgent.onPause(this);
  }

  private void getBabyAvatar(String remoteBabyAvatar) {
    SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
            Context.MODE_PRIVATE);

    String babyImagePath = prefs.getString(Constant.BABY_AVATAR, "");
    if (babyImagePath.equals("")) {

      new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected void onPostExecute(Bitmap result) {
          if (result != null) {
            String path = PathUtil.getBabyAvatarPath(getApplicationContext());
            FileOutputStream out = null;
            File babyAvatarFile = new File(path);
            try {
              out = new FileOutputStream(babyAvatarFile);
              result.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is
              // your
              // Bitmap
              // instance
              // PNG is a lossless format, the compression factor (100) is
              // ignored
              SharedPreferences prefs = getSharedPreferences(
                      Constant.USER_INFO, Context.MODE_PRIVATE);
              Uri babyAvatarUri = Uri.fromFile(babyAvatarFile);
              prefs.edit()
                      .putString(Constant.BABY_AVATAR, babyAvatarUri.toString())
                      .apply();
            } catch (Exception e) {
              e.printStackTrace();
            } finally {
              try {
                if (out != null) {
                  out.close();
                }
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
        }

        @Override
        protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap resultImage = null;
          URL url;
          try {
            url = new URL(urldisplay);

            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();

            urlConnection.setRequestMethod("GET");
            // urlConnection.setDoOutput(true);

            urlConnection.connect();

            InputStream in = urlConnection.getInputStream();

            // InputStream in = new java.net.URL(urldisplay).openStream();
            resultImage = BitmapFactory.decodeStream(in);

          } catch (MalformedURLException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          }
          return resultImage;
        }
      }.execute(remoteBabyAvatar);

    }
  }

  @Override
  protected void onResume() {
    super.onResume();

    MobclickAgent.onResume(this);

    if (!LeConfig.isDeviceConnect) {
      if (device_stateview != null) {
        device_stateview.setPlaying(false);
      }
    }

    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    if (mLeUser == null) {
      mLeUser = Tools.restoreLeUser();
    }

    final SocketThreadManager stm = SocketThreadManager.getInstance();
    //  stm.setDeviceStateListener(this);
    stm.removeDeviceStateListener(this);
    stm.setDeviceStateListener(this);

    stm.requestDeviceDetails();

    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        try {
          JSONObject jsonObject = new JSONObject();
          jsonObject.put("code", 202);
          jsonObject.put("act", "videostatu");
          SocketThreadManager.getInstance().send(jsonObject.toString());
        } catch (JSONException e) {
          e.printStackTrace();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }, 500);


    loadUnreadAudioMsg();
  }

  @Override
  protected void onNewIntent(Intent intent) {
    setIntent(intent);
    processExtraData();

    super.onNewIntent(intent);
  }

  @Override
  protected void onNetworkAvailable() {
    LeConfig.isInternetAvailable = true;
  }

  @Override
  protected void onNetworkDisconnect() {
    LeConfig.isInternetAvailable = false;

    if (device_stateview != null) {
      device_stateview.setPlaying(false);
    }
    super.onNetworkDisconnect();
  }

  boolean nonetwork;

  private void processExtraData() {
    Intent intent = getIntent();
    int pageIndex = -1;
    if (intent != null) {
      pageIndex = intent.getIntExtra("pageindex", 0);

      nonetwork = intent.getBooleanExtra("nonetwork", false);
    }

    if (pageIndex == 0) {
      viewPager.setCurrentItem(pageIndex, false);
      title_layout.setVisibility(View.VISIBLE);
      loadUnreadAudioMsg();
      setCurrentPage(pageIndex);
      mCurrentIndex = ENUM_PAGE.HOME_PAGE;
      // mLastIndex = mCurrentIndex;
    } else {
      title_layout.setVisibility(View.GONE);
    }

    if (pageIndex > 0) {
      setCurrentPage(pageIndex);
      viewPager.setCurrentItem(pageIndex, false);
    }

    if (nonetwork) {
      emptylayout.setVisibility(View.VISIBLE);
    } else {
      emptylayout.setVisibility(View.GONE);
    }
  }

  public interface MyTouchListener {
    public void onTouchEvent(MotionEvent event);
  }

  /*
   * 保存MyTouchListener接口的列表
   */
  private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<MyTouchListener>();

  /**
   * 提供给Fragment通过getActivity()方法来注册自己的触摸事件的方法
   *
   * @param listener
   */
  public void registerMyTouchListener(MyTouchListener listener) {
    myTouchListeners.add(listener);
  }

  /**
   * 提供给Fragment通过getActivity()方法来取消注册自己的触摸事件的方法
   *
   * @param listener
   */
  public void unRegisterMyTouchListener(MyTouchListener listener) {
    myTouchListeners.remove(listener);
  }

  @Override
  public boolean dispatchTouchEvent(MotionEvent event) {
    if (mCurrentIndex == ENUM_PAGE.HOME_PAGE) {
      for (MyTouchListener listener : myTouchListeners) {
        listener.onTouchEvent(event);
      }
    }

    return super.dispatchTouchEvent(event);
  }

  private void onActive() {
    LeConfig.isInternetAvailable = Tools.isNetworkAvailable(this);

    TabIndexFragment frag1 = new TabIndexFragment(this);
    //  TabAnimationFragment frag2 = new TabAnimationFragment(this);
    TabNewDiscoverFragment frag3 = new TabNewDiscoverFragment(this);
    TabMineFragment frag4 = new TabMineFragment(this);

    fragmentList.add(frag1);
    //fragmentList.add(frag2);
    fragmentList.add(frag3);
    fragmentList.add(frag4);

    viewPager.setOffscreenPageLimit(2);
    viewPager.setAdapter(new MyFragmentPagerAdapter2(
            getSupportFragmentManager(), fragmentList));
    viewPager.setPagingEnabled(false);
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
      @Override
      public void onPageSelected(int index) {
        if (index != 0) {
          title_layout.setVisibility(View.GONE);
        } else {
          loadUnreadAudioMsg();
          title_layout.setVisibility(View.VISIBLE);

          rel_sleeptip.setVisibility(View.GONE);
        }
        setCurrentPage(index);
      }

      @Override
      public void onPageScrolled(int arg0, float arg1, int arg2) {

      }

      @Override
      public void onPageScrollStateChanged(int arg0) {

      }
    });

    radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
          case R.id.radio_1:
            viewPager.setCurrentItem(0, false);
            mCurrentIndex = ENUM_PAGE.HOME_PAGE;
            // mLastIndex = mCurrentIndex;
            break;
          case R.id.radio_3:
            mCurrentIndex = ENUM_PAGE.DISCOVERY;
            viewPager.setCurrentItem(1, false);
            break;
          case R.id.radio_4:
            mCurrentIndex = ENUM_PAGE.PERSON_CENTER;
            viewPager.setCurrentItem(2, false);
            // mLastIndex = mCurrentIndex;
            break;
          default:
            break;
        }
      }
    });
  }

  private void setCurrentPage(int index) {
    RadioButton radio = (RadioButton) radioGroup.getChildAt(index);
    radio.setChecked(true);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    disableNetworkChangeListener();

    if (mReceiverTag) {
      mReceiverTag = false;
      this.unregisterReceiver(rh);
    }

    SocketThreadManager stm = SocketThreadManager.getInstance();
    stm.removeDeviceStateListener(this);
    if (mHandler != null) {
      mHandler.removeCallbacksAndMessages(null);
      mHandler = null;
    }


    MobclickAgent.onProfileSignOff();

    LePreference.getInstance().save("lastLaunchTime",
            System.currentTimeMillis());
  }

  @SuppressWarnings("static-access")
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
//      toastShow("再按一次退出" + getString(R.string.app_name));
//      isExitReady = true;
//      mHandler.postDelayed(new Runnable() {
//
//        @Override
//        public void run() {
//          isExitReady = false;
//        }
//      }, 1000);
      SocketThreadManager stm = SocketThreadManager.getInstance();
      try {
        stm.stopThreads();
      } catch (UnsupportedOperationException ee) {

      } catch (Exception e) {
        // TODO: handle exception
      }
      finish();
      return true;
    }
    return super.onKeyDown(keyCode,event);
  }

  private void checkForNewestVersion() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          AppVersion av = JsonSerializer.getInstance().deserialize(result.data,
              AppVersion.class);
          if (av != null) {
            int currentAppVersion;
            try {
              currentAppVersion = Integer.valueOf(getPackageManager()
                  .getPackageInfo(getPackageName(), 0).versionName.replaceAll(
                  "\\D+", ""));
              int newestAppVersion = Integer.valueOf(av.value.replaceAll(
                  "\\D+", ""));

              if (newestAppVersion > currentAppVersion) {
                startDownloadNewestVersion(av.value, av.download_url, av.desc);
              }

            } catch (NumberFormatException e) {
              e.printStackTrace();
            } catch (NameNotFoundException e) {
              e.printStackTrace();
            }

          }
        } else {
          if (Tools.isNotNullStr(result.data)) {
            Toast.makeText(getApplicationContext(), result.data,
                Toast.LENGTH_SHORT).show();
          }
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_PLATFORM_I, "android");
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/member/app/version", param_, HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  CustomUpdateDialog.Builder bbbb;
  DownloadTask mDownloadTask;
  CustomUpdateDialog mProgressDialog;

  private void startDownloadNewestVersion(final String remoteVersion,
      final String downloadUrl, String desc) {
    boolean usingGprs = isUsingGPRSConnection();
    if (usingGprs) {
      Toast.makeText(getApplicationContext(), "您当前正在使用移动流量!",
          Toast.LENGTH_SHORT).show();
    }

    bbbb = null;
    bbbb = new CustomUpdateDialog.Builder(this).setTitle("发现新版本")
        .setMessage("更新内容:\n" + desc)
        .setNegativeButton("", new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();

            stopService(new Intent(MainActivity.this, Net_Service.class));

            if (mDownloadTask != null) {
              mDownloadTask.cancel(true);
              mDownloadTask = null;
            }

            if (mProgressDialog != null) {
              mProgressDialog.dismiss();
              mProgressDialog = null;
            }
          }
        }).setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {

            if (mProgressDialog == null) {
              mProgressDialog = bbbb.create();
              mProgressDialog.setCancelable(true);
              mProgressDialog.setCanceledOnTouchOutside(false);
            }

            startService(new Intent(MainActivity.this, Net_Service.class));

            if (bbbb != null) {
              if (bbbb.umeng_update_frame != null) {
                bbbb.umeng_update_frame
                    .setBackgroundResource(R.drawable.update_dlg_bg2);
              }

              if (bbbb.pb_day != null) {
                bbbb.pb_day.setVisibility(View.VISIBLE);
              }

              if (bbbb.tv_filetip != null) {
                bbbb.tv_filetip.setVisibility(View.VISIBLE);
              }

              if (bbbb.tv_netspeed != null) {
                bbbb.tv_netspeed.setVisibility(View.VISIBLE);
              }

              if (bbbb.tv_wifi != null) {
                bbbb.tv_wifi.setVisibility(View.VISIBLE);
              }
            }

            mDownloadTask = new DownloadTask(MainActivity.this);
            mDownloadTask.execute(downloadUrl, remoteVersion);

            mProgressDialog
                .setOnCancelListener(new DialogInterface.OnCancelListener() {
                  @Override
                  public void onCancel(DialogInterface dialog) {

                    if (mDownloadTask != null) {
                      mDownloadTask.cancel(true);
                      mDownloadTask = null;
                    }

                    if (mProgressDialog != null) {
                      mProgressDialog.dismiss();
                      mProgressDialog = null;
                    }

                  }
                });
          }
        });

    if (!isFinishing()) {
      if (mProgressDialog == null) {
        mProgressDialog = bbbb.create();
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
      }
      mProgressDialog.show();

      if (bbbb != null) {
        if (bbbb.pb_day != null) {
          bbbb.pb_day.setVisibility(View.GONE);
        }

        if (bbbb.tv_filetip != null)
          bbbb.tv_filetip.setVisibility(View.GONE);

        if (bbbb.tv_netspeed != null) {
          bbbb.tv_netspeed.setVisibility(View.GONE);
        }

        if (bbbb.tv_wifi != null) {
          bbbb.tv_wifi.setVisibility(View.GONE);
        }

        if (bbbb.tv_version != null) {
          bbbb.tv_version.setText("V" + remoteVersion);
        }
      }
    }

  }

  // private CustomProgressDialog.Builder dlgBuilder;

  private boolean isUsingGPRSConnection() {
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
      if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
        if (ni.isConnected())
          haveConnectedMobile = true;
    }
    return haveConnectedMobile;
  }

  private class DownloadTask extends AsyncTask<String, Integer, String> {

    private final Context context;

    private PowerManager.WakeLock mWakeLock;

    public DownloadTask(Context context) {
      this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {
      InputStream input = null;
      OutputStream output = null;
      HttpURLConnection connection = null;
      try {
        URL url = new URL(sUrl[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        // expect HTTP 200 OK, so we don't mistakenly save error report
        // instead of the file
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
          return "Server returned HTTP " + connection.getResponseCode() + " "
              + connection.getResponseMessage();
        }

        // this will be useful to display download percentage
        // might be -1: server did not report the length
        int fileLength = connection.getContentLength();

        totalFileLen = fileLength;

        // download the file
        input = connection.getInputStream();
        String downloadPath = Environment.getExternalStorageDirectory()
            .getAbsolutePath();
        downloadPath += "/download/" + "com.jdy.haoduoai" + sUrl[1]
            + ".apk";

        File mFolder = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/download/");
        if (!mFolder.exists()) {
          mFolder.mkdir();
        }

        output = new FileOutputStream(downloadPath);

        byte data[] = new byte[4096];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
          // allow canceling with back button
          if (isCancelled()) {
            input.close();
            return null;
          }
          total += count;

          downloadLen = (int) total;

          // publishing the progress....
          if (fileLength > 0) // only if total length is known
            publishProgress((int) (total * 100 / fileLength));
          output.write(data, 0, count);
        }
        return downloadPath;
      } catch (Exception e) {
        return e.toString();
      } finally {
        try {
          if (output != null)
            output.close();
          if (input != null)
            input.close();
        } catch (IOException ignored) {
        }

        if (connection != null)
          connection.disconnect();
      }
    }

    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      // take CPU lock to prevent CPU from going off if the user
      // presses the power button during download
      PowerManager pm = (PowerManager) context
          .getSystemService(Context.POWER_SERVICE);
      mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass()
          .getName());
      mWakeLock.acquire();
      // if (!isFinishing()) {
      // mProgressDialog.show();
      // }
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
      super.onProgressUpdate(progress);

      bbbb.pb_day.setMax(100);
      bbbb.pb_day.setProgress(progress[0]);
      bbbb.tv_netspeed.setText(netSpeed);
      bbbb.tv_filetip.setText(Html.fromHtml("<font color =\"#4fbafc\">"
          + android.text.format.Formatter.formatFileSize(MainActivity.this,
              downloadLen)
          + "/"
          + "</font>"
          + android.text.format.Formatter.formatFileSize(MainActivity.this,
              totalFileLen)));
    }

    @Override
    protected void onPostExecute(String result) {
      mWakeLock.release();

      if (mProgressDialog != null) {
        mProgressDialog.dismiss();
        mProgressDialog = null;
      }

      stopService(new Intent(MainActivity.this, Net_Service.class));

      if (result == null || result.startsWith("Server")) {
        if (result != null)
          Toast.makeText(context, "Download error: " + result,
              Toast.LENGTH_LONG).show();
      } else // download successfully!
      {
        Toast
            .makeText(context, "File downloaded :" + result, Toast.LENGTH_LONG)
            .show();

        SharedPreferences prefs = getSharedPreferences(Constant.WELCOME_PAGE,
            Context.MODE_PRIVATE);
        prefs.edit().putBoolean(Constant.HAS_ILLUSTRATED, false).apply();

        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(result);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file),
            "application/vnd.android.package-archive");
        startActivity(intent);
      }
    }
  }

  private int totalFileLen, downloadLen;

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.device_stateview:
//      if (LeConfig.isLogin) {
        startActivity(new Intent(this, DevicePropertyActivity.class));

//      } else {
//        Intent intent = new Intent(this, LoginActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        startActivity(intent);
//      }
      break;

    case R.id.img_search:
//      if (LeConfig.isLogin) {
        Intent toSearch = new Intent(this, SearchActivity.class);
        toSearch.putExtra("type", "cartoon");
        startActivity(toSearch);
//      } else {
//        Intent intent = new Intent(this, LoginActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        startActivity(intent);
//      }
      break;
    case R.id.playmode:
      // toastShow("change play order");
      break;

    default:
      break;
    }
  }

  private void loadUnreadAudioMsg() {

    new CustomAsyncTask(this, new IAsyncTask() {
      @SuppressLint("SimpleDateFormat")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          if (Tools.isNotNullStr(result.data)) {
            int num = Integer.valueOf(result.data);
            if (num > 0) {
              if (img_redicon == null) {
                img_redicon = (ImageView) findViewById(R.id.img_redicon);
              }

              img_redicon.setVisibility(View.VISIBLE);

              if (tv_soundnum == null) {
                tv_soundnum = (TextView) title_layout
                    .findViewById(R.id.tv_soundnum);
              }

              tv_soundnum.setText(result.data);
              tv_soundnum.setVisibility(View.VISIBLE);
            } else {
              if (img_redicon == null) {
                img_redicon = (ImageView) findViewById(R.id.img_redicon);
              }
              img_redicon.setVisibility(View.GONE);

              if (tv_soundnum == null) {
                tv_soundnum = (TextView) title_layout
                    .findViewById(R.id.tv_soundnum);
              }
              tv_soundnum.setVisibility(View.GONE);
            }
          }
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/member/history/sound/unread_audio_number", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  public class ReceiverHandler extends BroadcastReceiver {
    private Context context = null;

    public ReceiverHandler(Context context) {
      this.context = context;
    }

    public void registerAction(String action) {
      IntentFilter filter = new IntentFilter();
      filter.addAction(action);
      context.registerReceiver(this, filter);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if ("sound_msg_received".equals(action)
          || "com.jdy.haoduoai.activity.NOTIFICATION_SHOW".equals(action)) {
        loadUnreadAudioMsg();
      }

      if ("com.jdy.haoduoai.speed".equals(action)) {
        netSpeed = intent.getStringExtra("speed");
      }
    }
  }

  String netSpeed = "";

  @Override
  public void onRemoteLogin() {
    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        if (device_stateview != null) {
          device_stateview.setPlaying(false);
        }
      }
    });
  }

  @Override
  public void onConnectionChanged(boolean connect) {

  }

  @Override
  public void onPowerChanged(int power) {

  }

  @Override
  public void onUpgrade(int updatingStatus) {

  }

  @Override
  public void onCheckDeviceVersion(String version) {

  }

  @Override
  public void onPlayNextFailed() {

  }

  @Override
  public void onPlayPrevFailed() {

  }

  @Override
  public void onPlayMedia(final PlayState playState, final MediaType type,
                          final JSONObject data) {

    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        if (playState.equals(PlayState.Playing)) {
          device_stateview.setPlaying(true);
        } else {
          device_stateview.setPlaying(false);
        }

        if (!playState.equals(PlayState.Playing)) {
          mMediaType = type;
        }
        if (playState.equals(PlayState.Offline)) {
          mMediaType = MediaType.None;
        } else if (playState.equals(PlayState.NoResource)
            || playState.equals(PlayState.Stop)) {
          mMediaType = MediaType.None;
        } else if (PlayState.Pause.equals(playState)
            || PlayState.Playing.equals(playState)) {
          if (Tools.isNotEmpty(data) && data.has("VideoName")) {
            // TODO
          }
        }
      }
    });

  }

  @Override
  public void onReceivedVoiceMessage(String streamUrl) {

  }

  @Override
  public void onDataReceived(String data) {
    // TODO
  }
}
